//
//  BalanceDetailViewController.m
//  Balance
//
//  Created by Calvin Kuo on 12-03-22.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "BalanceDetailViewController.h"
#import "EskPlotTheme.h"
#import "ColorUtility.h"

#define TIME_FOR_SHRINKING 0.61f // Has to be different from SPEED_OF_EXPANDING and has to end in 'f'
#define TIME_FOR_EXPANDING 0.60f // Has to be different from SPEED_OF_SHRINKING and has to end in 'f'
#define SCALED_DOWN_AMOUNT 0.01  // For example, 0.01 is one hundredth of the normal size

/*
 Status: changed
 Last Merge Date: 05-30-2012
 Last Change Date: 
 Changes:
 1. separator and button animation
 */



@interface BalanceDetailViewController ()
@property (strong, nonatomic) UIPopoverController *masterPopoverController;
- (void)configureView;
@end

@implementation BalanceDetailViewController

@synthesize scrollView = _scrollView;
@synthesize pageControl = _pageControl;
@synthesize detailItem = _detailItem;
@synthesize lineHostingView = _lineHostingView;
@synthesize barHostingView = _barHostingView;
@synthesize sliderHostingView = _sliderHostingView;
@synthesize masterPopoverController = _masterPopoverController;
@synthesize selectedCountryNames = _selectedCountryNames;
@synthesize selectedCountryBalances = _selectedCountryBalances;
@synthesize countryBarHostingView = _countryBarHostingView;
@synthesize agingDateLabel = _agingDateLabel;
@synthesize currentAmountButton = _currentAmountButton;
@synthesize separator = _separator;
@synthesize viewController = _viewController;
@synthesize notesButton = _notesButton;
@synthesize detailsButton = _detailsButton;
@synthesize buttonsView = _buttonsView;
@synthesize objectType = _objectType;
@synthesize spinner = _spinner;

#define kNumberOfPages 2

#pragma mark - Managing the detail item

- (void) setDetailsButton:(UIButton *)detailsButton
{
    _detailsButton = detailsButton;
    CAGradientLayer *gradientLayer = [ColorUtility buttonGradientLayer];
    
    gradientLayer.frame = _detailsButton.layer.bounds;
    [_detailsButton.layer insertSublayer:gradientLayer atIndex:0];
    _detailsButton.titleLabel.textColor = [UIColor whiteColor];
}

- (void) setNotesButton:(UIButton *)notesButton
{
    _notesButton = notesButton;
    CAGradientLayer *gradientLayer = [ColorUtility buttonGradientLayer];
    
    gradientLayer.frame = _notesButton.layer.bounds;
    [_notesButton.layer insertSublayer:gradientLayer atIndex:0];
    _notesButton.titleLabel.textColor = [UIColor whiteColor];
    
}

- (void) setButtonsView:(UIView *)buttonsView
{
    _buttonsView = buttonsView;
    
    CAGradientLayer *gradientLayer = [ColorUtility toolBarGradientLayer];
    
    gradientLayer.frame = _buttonsView.layer.bounds;
    [_buttonsView.layer insertSublayer:gradientLayer atIndex:0];
}

- (void)setDetailItem:(id)newDetailItem
{
    if (_detailItem != newDetailItem) {
        _detailItem = newDetailItem;
        
        // Update the view.
        [self configureView];
    }

    if (self.masterPopoverController != nil) {
        [self.masterPopoverController dismissPopoverAnimated:YES];
    }        
}

- (void)configureView
{
    // Update the user interface for the detail item.

    /* calvin: I removed this label.
     if (self.detailItem) {
        self.detailDescriptionLabel.text = [self.detailItem description];
    }
     */
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    [self configureView];
    
    
    self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * kNumberOfPages, self.scrollView.frame.size.height);
    
    self.scrollView.delegate = self;
    self.view.backgroundColor = [UIColor colorWithWhite:0.7f alpha:1.0f];
    
    currentAmountDisplayed = YES;
    _currentAmountButton.hidden = YES;
    _separator.hidden = YES;
    
    _spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    _spinner.frame=CGRectMake(330, 350, 25, 25);
    //_spinner.frame = CGRectMake(round((self.view.frame.size.width - 25) / 2), round((self.view.frame.size.height - 25) / 2), 25, 25);
    _spinner.tag  = 1;
    [self.view addSubview:_spinner];
    
    [_spinner startAnimating];
    [NSThread detachNewThreadSelector:@selector(drawGraphs) toTarget:self withObject:nil];
    
    
    
    
    currentAmountDisplayed = YES;
    //_currentAmountButton.hidden = NO;
    
}


- (void)drawGraphs{
    
    EskPlotTheme *defaultTheme = [[EskPlotTheme alloc] init];
    
    barPlot = [[EskBarPlot alloc] init];
    barPlot.delegate = self;
    
    [barPlot renderInLayer:_barHostingView withTheme:defaultTheme];
    
    
    linePlot = [[EskLinePlot alloc] init];
    linePlot.delegate = self;
    [linePlot renderInLayer:_lineHostingView withTheme:defaultTheme];
    
    sliderLinePlot = [[SliderPlot alloc] init];
    sliderLinePlot.delegate = self;
    [sliderLinePlot renderInLayer:_sliderHostingView withTheme:defaultTheme];
    
    
    //Set the initial date of the aging bucket displayed in the label
    NSDate *today = [NSDate date];
    NSDateFormatter *usFormat = [[NSDateFormatter alloc] init];    
    //[usFormat setDateStyle:NSDateFormatterMediumStyle];//May 30, 2012
    [usFormat setDateFormat:@"MM/dd/yyyy"];
    NSString *todayString = [usFormat stringFromDate:today];
    _agingDateLabel.text = todayString;
    
    
    //View By Country
    BalanceModel *bm = [[BalanceModel alloc] init];
    
    NSMutableArray *initCountryNames = [[NSMutableArray alloc] init];
    NSMutableArray *initCountryBalances = [[NSMutableArray alloc] init];
    NSString *countryOne=@"Brazil";
    NSString *countryTwo=@"China";
    NSString *countryThree=@"India";
    NSString *countryFour=@"Mexico";
    NSString *countryFive=@"Russia";
    [initCountryNames addObject:@""];
    [initCountryBalances addObject:[NSNull null]];
    [initCountryNames addObject:countryOne];
    [initCountryBalances addObject:[bm.countryBalances objectForKey:countryOne]];
    [initCountryNames addObject:countryTwo];
    [initCountryBalances addObject:[bm.countryBalances objectForKey:countryTwo]];
    [initCountryNames addObject:countryThree];
    [initCountryBalances addObject:[bm.countryBalances objectForKey:countryThree]];
    [initCountryNames addObject:countryFour];
    [initCountryBalances addObject:[bm.countryBalances objectForKey:countryFour]];
    [initCountryNames addObject:countryFive];
    [initCountryBalances addObject:[bm.countryBalances objectForKey:countryFive]];
    
    countryBarPlot = [[CountryBarPlot alloc] initWithCountryNames:initCountryNames andCountryBalances:initCountryBalances];     
    
    [countryBarPlot renderInLayer:_countryBarHostingView withTheme:defaultTheme];
    
    _separator.hidden = NO;
    _currentAmountButton.hidden = NO;
    
    [_spinner stopAnimating];
    
}


- (void)viewDidUnload
{
    [self setLineHostingView:nil];
    [self setBarHostingView:nil];
    [self setSliderHostingView:nil];
    [self setScrollView:nil];
    [self setPageControl:nil];
    [self setCountryBarHostingView:nil];
    [self setAgingDateLabel:nil];
    [self setCurrentAmountButton:nil];
    [self setSeparator:nil];
    [self setNotesButton:nil];
    [self setDetailsButton:nil];
    [self setButtonsView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self performSelector:@selector(animateTransition:) withObject:[NSNumber numberWithFloat: TIME_FOR_SHRINKING]];	
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return YES;
}

//Current Balance Switch

-(void)changeButtonImage:(UIImage *)buttonImage{
    
    [_currentAmountButton setImage:buttonImage forState:UIControlStateNormal];
}

- (IBAction)addCurrentAmount:(id)sender {
      
    if (currentAmountDisplayed){
        
        CGRect separatorFrame = _separator.frame;
        separatorFrame.origin.x = 90.0;
        //NSLog(@"frame x = %f",separatorFrame.origin.x);
        
        CGRect buttonFrame = _currentAmountButton.frame;
        buttonFrame.origin.x = 82.0;
        //NSLog(@"frame x = %f",buttonFrame.origin.x);
      
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.35];
        [UIView setAnimationDelay:0.0];
        [UIView setAnimationCurve:UIViewAnimationCurveLinear];
        _separator.frame = separatorFrame;
        _currentAmountButton.frame = buttonFrame;
        
        [UIView commitAnimations];
         
        [barPlot barPlot:barPlot respondToCurrentBalanceSwitch:NO];
        currentAmountDisplayed = NO;
        //[self performSelector:@selector(changeButtonImage:) withObject:leftArrow afterDelay:2.0f];
    }
    else{
        
        CGRect separatorFrame = _separator.frame;
        separatorFrame.origin.x = 230.0;
        //NSLog(@"frame x = %f",separatorFrame.origin.x);
        
        CGRect buttonFrame = _currentAmountButton.frame;
        buttonFrame.origin.x = 222.0;
        //NSLog(@"frame x = %f",buttonFrame.origin.x);
        
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.35];
        [UIView setAnimationDelay:0.0];
        [UIView setAnimationCurve:UIViewAnimationCurveLinear];
        
        _separator.frame = separatorFrame;
        _currentAmountButton.frame = buttonFrame;
        
        [UIView commitAnimations];

        
        
        [barPlot barPlot:barPlot respondToCurrentBalanceSwitch:YES];
        currentAmountDisplayed = YES;
        //[self performSelector:@selector(changeButtonImage:) withObject:rightArrow afterDelay:2.0f];
        //[_currentAmountButton setImage:rightArrow forState:UIControlStateNormal];
    }

    
}


#pragma mark - Split view

- (void)splitViewController:(UISplitViewController *)splitController willHideViewController:(UIViewController *)viewController withBarButtonItem:(UIBarButtonItem *)barButtonItem forPopoverController:(UIPopoverController *)popoverController
{
    barButtonItem.title = NSLocalizedString(@"Master", @"Master");
    [self.navigationItem setLeftBarButtonItem:barButtonItem animated:YES];
    self.masterPopoverController = popoverController;
}

- (void)splitViewController:(UISplitViewController *)splitController willShowViewController:(UIViewController *)viewController invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem
{
    // Called when the view is shown again in the split view, invalidating the button and popover controller.
    [self.navigationItem setLeftBarButtonItem:nil animated:YES];
    self.masterPopoverController = nil;
}

#pragma mark - BarPlot delegate

- (void)barPlot:(EskBarPlot *)plot barWasSelectedAtRecordIndex:(NSUInteger)index currentBalanceDisplayed:(BOOL)switchOn
{
   /* calvin 
     selectedProductLabel.text = [NSString stringWithFormat:@"Aging Period: %@", [plot.sampleProduct objectAtIndex:index]];
    costPerUnitLabel.text = [NSString stringWithFormat:@"Amount Overdue: $%@", [plot.sampleData objectAtIndex:index]];
    */
    
    //NSLog(@"bar was selected at %i and current displayed =%d", index, switchOn);
    
    TransactionViewController *tvc = [self.storyboard instantiateViewControllerWithIdentifier:@"transactionVC"];

    if (index == 1) {
        tvc.bucketType = [NSString stringWithFormat:@"%@ Transactions", [plot.agingLabels objectAtIndex:index]];
    } else {
        tvc.bucketType = [NSString stringWithFormat:@"%@ Days Overdue Transactions", [plot.agingLabels objectAtIndex:index]];
    }
//    [self.navigationController pushViewController:tvc animated:NO];
  
    self.viewController = tvc;
	[self performSelector:@selector(animateTransition:) withObject:[NSNumber numberWithFloat: TIME_FOR_EXPANDING]];
/*    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:1.0];
    //[UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.navigationController.view cache:YES];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.navigationController.view cache:YES];
    [self.navigationController pushViewController:tvc animated:NO];
    [UIView commitAnimations];
*/    
    //[self transitionFromViewController:self toViewController:tvc duration:1.0 options:UIViewAnimationOptionTransitionFlipFromRight animations:nil completion:nil];
}

-(void)animateTransition:(NSNumber *)duration {
	self.view.userInteractionEnabled=NO;
	[[self view] addSubview:self.viewController.view];
	if ((self.viewController.view.hidden==false) && ([duration floatValue]==TIME_FOR_EXPANDING)) {
		self.viewController.view.frame=[[UIScreen mainScreen] bounds];
		self.viewController.view.transform=CGAffineTransformMakeScale(SCALED_DOWN_AMOUNT, SCALED_DOWN_AMOUNT);
	}
	self.viewController.view.hidden=false;
	if ([duration floatValue]==TIME_FOR_SHRINKING) {
		[UIView beginAnimations:@"animationShrink" context:NULL];
		[UIView setAnimationDuration:[duration floatValue]];
		self.viewController.view.transform=CGAffineTransformMakeScale(SCALED_DOWN_AMOUNT, SCALED_DOWN_AMOUNT);
	}
	else {
		[UIView beginAnimations:@"animationExpand" context:NULL];
		[UIView setAnimationDuration:[duration floatValue]];
		self.viewController.view.transform=CGAffineTransformMakeScale(1, 1);
	}
	[UIView setAnimationDelegate:self];
	[UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];
	[UIView commitAnimations];
}
-(void)animationDidStop:(NSString *)animationID finished:(BOOL)finished context:(void *)context{
	self.view.userInteractionEnabled=YES;
	if ([animationID isEqualToString:@"animationExpand"]) {
		[[self navigationController] pushViewController:self.viewController animated:NO];
	}
	else {
		self.viewController.view.hidden=true;
	}
}


#pragma mark - LinePlot delegate
/*
- (void)linePlot:(EskLinePlot *)plot indexLocation:(NSUInteger)index
{  
    // calvin
    //selectedYearLabel.text = [NSString stringWithFormat:@"Selected Year/Month: %@", [plot.sampleYears objectAtIndex:index]];
    //spendingPerYearLabel.text = [NSString stringWithFormat:@"Balance: $%@", [plot.sampleData objectAtIndex:index]];
    
    //lineplot calls the bar plot to change accordingly
    //NSLog(@"calling index: %d and indexe%6=", index, index%6);

    [barPlot barPlot:barPlot respondToLinePlotSelectedAtRecordIndex:(index%7 +1)];
}
*/

- (void)linePlot:(EskLinePlot *)plot selectedDate:(NSString *)selectedDateString
{
    //NSLog(@"selectedDateString=%@",selectedDateString);
    [barPlot barPlot:barPlot respondToLinePlotSelectedAtDate:(selectedDateString)];
    
    
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyyMMdd"];
    NSDate *selectedDate = [df dateFromString: selectedDateString];
    NSDateFormatter *usFormat = [[NSDateFormatter alloc] init];    
    [usFormat setDateStyle:NSDateFormatterMediumStyle];
    //[usFormat setDateFormat:@"MM/dd/yyyy"];
    NSString *displayString = [usFormat stringFromDate:selectedDate];
    _agingDateLabel.text = displayString;
}


#pragma mark - SliderPlot delegate

- (void)linePlot:(SliderPlot *)plot indexLocation:(NSUInteger)index{
    //NSLog(@"implement sliderplot delegate in BalanceDetailViewController.m");
}

-(void)sliderPlot:(SliderPlot *)plot fromDate:(NSString *)fromDateString toDate:(NSString *)toDateString
{
    //NSLog(@"model fromDateString=%@",fromDateString);
    //NSLog(@"model toDateString=%@",toDateString);
    [linePlot linePlot:linePlot respondToRangeChangeFromDate:fromDateString toDate:toDateString];
    
    //[barPlot barPlot:barPlot respondToLinePlotSelectedAtDate:(selectedDateString)];
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)sender {
    // Update the page when more than 50% of the previous/next page is visible
    CGFloat pageWidth = self.scrollView.frame.size.width;
    int page = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    self.pageControl.currentPage = page;
   
}


- (IBAction)changePage {
    // update the scroll view to the appropriate page
    CGRect frame;
    frame.origin.x = self.scrollView.frame.size.width * self.pageControl.currentPage;
    frame.origin.y = 0;
    frame.size = self.scrollView.frame.size;
    [self.scrollView scrollRectToVisible:frame animated:YES];

    /*
    if (_currentAmountButton.hidden)
        _currentAmountButton.hidden = NO;
    else
        _currentAmountButton.hidden = YES;
    */
}



- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    pageControlBeingUsed = NO;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    pageControlBeingUsed = NO;
}



@end
